package net.wanho.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-08-24 16:52
 * Description：Jwt工具类
 */
public class JwtUtils {

    // 过期时间
    private static final int MINUTE = 30;

    // 密钥
    private static final String SECRET = "wanho";

    /**
     * 生成令牌
     * @param payload
     * @return
     */
    public static String generate(Map<String,Object> payload){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE,MINUTE);

        String token = JWT.create()
                .withPayload(payload) // 设置载荷
                .withExpiresAt(c.getTime()) // 设置过期时间
                .sign(Algorithm.HMAC256(SECRET));// 设置签名

        return token;
    }

    /**
     * 验证令牌
     * 如果令牌过期，会报TokenExpiredException异常
     */
    public static boolean valid(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 解析令牌
     */
    public static Integer parseInteger(String token,String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256("wanho")).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static String parseString(String token,String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256("wanho")).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }

}
